﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Silverlight3dApp.Learning.Lesson03
{
    public class SpriteManager : DrawableGameComponent
    {
        private SpriteBatch _spriateBatch;
        private UserControlledSprite _player;
        private readonly List<AutomatedSprite> _sprites = new List<AutomatedSprite>();

        public SpriteManager(Game game) : base(game)
        {
        }

        protected override void LoadContent()
        {
            _spriateBatch = new SpriteBatch(Game.GraphicsDevice);
            _player = new UserControlledSprite(Game.Content.Load<Texture2D>(@"Images/threerings"), Vector2.Zero, new Vector2(75, 75), 10, new Vector2(0, 0), new Vector2(6, 8), new Vector2(5, 5));
            _sprites.Add(new BouncingSprite(Game.Content.Load<Texture2D>(@"Images/skullball"), new Vector2(150, 150), new Vector2(75, 75), 10, new Vector2(0, 0), new Vector2(6, 8), new Vector2(6, 6)));
            _sprites.Add(new BouncingSprite(Game.Content.Load<Texture2D>(@"Images/skullball"), new Vector2(300, 150), new Vector2(75, 75), 10, new Vector2(0, 0), new Vector2(6, 8), new Vector2(4, 7)));
            _sprites.Add(new BouncingSprite(Game.Content.Load<Texture2D>(@"Images/skullball"), new Vector2(150, 300), new Vector2(75, 75), 10, new Vector2(0, 0), new Vector2(6, 8), new Vector2(8, 3)));
            _sprites.Add(new BouncingSprite(Game.Content.Load<Texture2D>(@"Images/skullball"), new Vector2(600, 400), new Vector2(75, 75), 10, new Vector2(0, 0), new Vector2(6, 8), new Vector2(5, 5)));
            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            _player.Update(gameTime, Game.GraphicsDevice.Viewport.Bounds);
            foreach (var sprite in _sprites)
            {
                sprite.Update(gameTime, Game.GraphicsDevice.Viewport.Bounds);
                if (sprite.CollisionRectangle.Intersects(_player.CollisionRectangle))
                {
                    Game.Exit();
                }
            }
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            _spriateBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
            _player.Draw(gameTime, _spriateBatch);
            foreach (var sprite in _sprites)
            {
                sprite.Draw(gameTime, _spriateBatch);
            }
            _spriateBatch.End();
            base.Draw(gameTime);
        }
    }
}